<?php
    function my_autoload ($pClassName) {
        include($pClassName . ".php");
    }
    spl_autoload_register("my_autoload");
    
    class ClientAdapter {
        private $socketadapter;
        private $dbadapter;
        
        public function __construct() {
            
        }
        
        public function __destruct() {
            $this->socketadapter->__destruct();
            $this->dbadapter->__destruct();             
        }
        
        public function start() {
            $this->socketadapter = new socket_adapter();
            $this->socketadapter->listen();
            
            if ($this->db_connect()) {
                do {
                    $bytes = $this->routine();
                }
                while($bytes != 0);
            }    
        }
        
        private function routine() {

            $input = $this->socketadapter->read();
            
            if ($input == null) {
                echo "NULL";
                // клиент отсоединился
                return 0;    
            } 
            $obj = json_decode($input);
            
            if ($obj->{'type'} == "exit") {
                echo "EXIT";
                $this->socketadapter->write("accept");
                return 0;
            } 
            
            if ($obj->{'type'} == "query") {
                $res = $this->dbadapter->query($obj->{'value'});
                
                
                $rows = array();
                while($r = mysql_fetch_assoc($res)) {
                    $rows[] = $r;
                }
                $output = json_encode($rows);
                
                $output = encoder::to_utf8($output);
                
                echo "output $output";
                
                
                $this->socketadapter->write($output);
            }
            
            return 1;        
        }
        
        private function db_connect() {
            
            $input = $this->socketadapter->read();
            if ($input == null) {
                echo "null";
                return false;    
            } 
            
            $obj = json_decode($input);
            if ($obj->{'type'} == "exit") {
                $this->socketadapter->write("accept");
                return false;
            } 
            
            if ($obj->{'type'} == "db_args") {

                $this->dbadapter = new db_adapter();
                $this->dbadapter->init($obj->{'database'}, $obj->{'user'}, $obj->{'password'});
                $this->socketadapter->write("accept");
            }   
            return true;
        }
        
        
                
         
    }

    $clientadapter = new ClientAdapter();
    $clientadapter->start();
    $clientadapter->__destruct();
?>
